<template>
  <div>
    <h1 v-if="$route.query.type === 'user'">导入员工信息</h1>
    <upload-excel :on-success="success" />
  </div>
</template>

<script>
import { importEmployees } from '@/api/employees'
export default {
  methods: {
    async success(data) {
      console.log(data)
      // 1. 处理数据
      const res = this.formateData(data)
      // 2.发送请求
      await importEmployees(res)
      this.$message.success('导入成功')
    },
    // 整理数据
    formateData(data) {
      const userRelations = {
        入职日期: 'timeOfEntry',
        姓名: 'username',
        工号: 'workNumber',
        手机号: 'mobile',
        转正日期: 'correctionTime'
      }
      const arr = []
      data.results.forEach((item) => {
        const obj = {}
        Object.keys(userRelations).forEach((key) => {
          // key就是每个中文键
          // console.log(item[key]) // 每个中文对应的数据值
          // console.log(userRelations[key]) // 每个中文对应的英文名
          if (['timeOfEntry', 'correctionTime'].includes(userRelations[key])) {
            obj[userRelations[key]] = this.formatDate(item[key], '/')
          } else {
            obj[userRelations[key]] = item[key]
          }
        })
        arr.push(obj)
      })
      return arr
    },
    // 处理日期
    formatDate(numb, format) {
      const time = new Date((numb - 1) * 24 * 3600000 + 1)
      time.setYear(time.getFullYear() - 70)
      const year = time.getFullYear() + ''
      const month = time.getMonth() + 1 + ''
      const date = time.getDate() - 1 + ''
      if (format && format.length === 1) {
        return year + format + month + format + date
      }
      return (
        year +
        (month < 10 ? '0' + month : month) +
        (date < 10 ? '0' + date : date)
      )
    }
  }
}
</script>
